(function(){
    
    angular.module("app.tool",[])
        .factory('proxy',['$http',"$q",proxy]);

        function proxy($http,$q) {
            var service = {
                post: post,
                // 兼容旧代码
                proxy: post,
            }

            return service;

            function post (option) {
                var defer, loadId;
                // 判断token是否存在
                if(!token && !option.data.token) {
                    location.href = "./login.html";
                    return;
                }
                // 判断是否使用全局token
                if(!option.data.token) option.data.token = token;
                if(option.load) {
                    loadId = layer.load(1,{shade:0.3})
                }
                defer = $q.defer();
                $http({
                    'url': option.url,
                    'method': 'post',
                    'data': JSON.stringify(option.data)
                }).then(function (response) {
                    if(loadId) layer.close(loadId);
                    if (response.data.status == "0") {
                        // return response.data;
                        option.success && option.success(response.data);
                        defer.resolve(response.data);
                    } else if(response.data.errCode == 88002){
                       
                        throw new Error("登录失效,请重新登录");
                    } else {
                        throw new Error(response.data.error);
                    }
                },function(){
                    throw new Error("网络连接失败，请稍后再试");
                }).catch(function(error) {
                    if(loadId) layer.close(loadId);
                    layer.msg(error.message);
                    defer.reject(error);
                    option.error && option.error(error);
                    if(error.message == "登录失效,请重新登录") {
                        setTimeout(function(){
                            location.href = "./login.html";
                        },2000)
                    }
                });


                return defer.promise;
            }
        }
})();